package com.bonc.ioc.demo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @projectName: sdvp
 * @description: 跨站请求伪造过滤器
 * @author: Liyy
 * @create: 2020-08-21 15:43
 **/
public class CSRFilter implements Filter {

    /**
     * 跨站请求伪造的餐数
     */
    private String referer;

    public CSRFilter(String referer) {
        this.referer = referer;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //防止跨站点请求伪造，对Referer验证
        String referer = request.getHeader("Referer");
        //如果referer为空，则认为该请求存在风险
        if (referer == null) {
            System.out.println("请求伪造");
            response.sendRedirect(request.getContextPath() + "/sys/error/csrf");
            return;
        }

        //如果referer中包括服务端的地址与ip，则证明是后台请求，无需拦截，自动放行
        if (referer.contains(request.getLocalAddr()) && referer.contains(String.valueOf(request.getServerPort()))) {
            filterChain.doFilter(request, response);
            return;
        }

        //如果refere中的地址不是指定安全地址，则说明存在风险
        if (!(referer.trim().contains(this.referer))) {
            System.out.println("请求伪造");
            response.sendRedirect(request.getContextPath() + "/sys/error/csrf");
            return;
        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
